/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufrn.dimap.projetodetalhadodesoftware.chatrmi.view.gui;

import br.ufrn.dimap.projetodetalhadodesoftware.chatrmi.model.actor.ChatModel;
import br.ufrn.dimap.projetodetalhadodesoftware.chatrmi.controller.exception.ObjectNotFoundExeption;
import br.ufrn.dimap.projetodetalhadodesoftware.chatrmi.view.ChatView;
import br.ufrn.dimap.projetodetalhadodesoftware.chatrmi.controller.ChatController;
import br.ufrn.dimap.projetodetalhadodesoftware.chatrmi.controller.ChatControllerInterface;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Random;
import javax.swing.JOptionPane;

/**
 *
 * @author logan
 */
public class ChatGUIWindow extends javax.swing.JFrame implements ChatView {

    /**
     * Creates new form ChatWindow
     */
    ChatControllerInterface chatControllerInterface;
     ChatController chatController;

    public ChatGUIWindow() {
        initComponents();

    }


    public void connect() throws RemoteException, NotBoundException, MalformedURLException, ObjectNotFoundExeption{

        int numMaxClients = Integer.parseInt(jTextFieldNumMaxOfClients.getText());
        int port = getNumPort();
        String theme = jTextFieldTheme.getText().trim();

        chatControllerInterface = new ChatController(new ChatModel(numMaxClients, theme), this,"localhost", port);
        chatControllerInterface.createRegister();
        chatControllerInterface.connectToServer();
    }

    private int getNumPort(){
        Random random = new Random();

        return 1025 + random.nextInt(60000);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaTalks = new javax.swing.JTextArea();
        jLabelTheme = new javax.swing.JLabel();
        jTextFieldTheme = new javax.swing.JTextField();
        jButtonConnect = new javax.swing.JButton();
        jLabelTheme1 = new javax.swing.JLabel();
        jTextFieldNumMaxOfClients = new javax.swing.JFormattedTextField();
        jLabelIPPortLabel = new javax.swing.JLabel();
        jLabelIPPort = new javax.swing.JLabel();
        jLabelIPPortLabel1 = new javax.swing.JLabel();
        jLabelMaxAndConnected = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("CHAT");
        setResizable(false);

        jTextAreaTalks.setColumns(20);
        jTextAreaTalks.setEditable(false);
        jTextAreaTalks.setRows(5);
        jScrollPane1.setViewportView(jTextAreaTalks);

        jLabelTheme.setText("Assunto");

        jButtonConnect.setText("Conectar");
        jButtonConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonConnectActionPerformed(evt);
            }
        });

        jLabelTheme1.setText("Capacidade");

        try {
            jTextFieldNumMaxOfClients.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        jLabelIPPortLabel.setText("IP/Port:");

        jLabelIPPort.setText("127.0.0.1/56445");

        jLabelIPPortLabel1.setText("Cap/Conectados:");

        jLabelMaxAndConnected.setText("60/15");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabelIPPortLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabelMaxAndConnected))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabelIPPortLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabelIPPort))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabelTheme)
                            .addComponent(jLabelTheme1))
                        .addGap(31, 31, 31)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jTextFieldTheme, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(138, 138, 138)
                                .addComponent(jButtonConnect))
                            .addComponent(jTextFieldNumMaxOfClients, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 551, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(25, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabelTheme)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextFieldTheme, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButtonConnect)))
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelTheme1)
                    .addComponent(jTextFieldNumMaxOfClients, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(16, 16, 16)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelIPPortLabel)
                    .addComponent(jLabelIPPort))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelIPPortLabel1)
                    .addComponent(jLabelMaxAndConnected))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConnectActionPerformed
         try {
            connect();
            jTextAreaTalks.append("conectado!! ID:"+chatControllerInterface.getId());

        } catch (RemoteException ex) {
            JOptionPane.showMessageDialog(this,"Erro ao se conectar!\n Tente novamente agora ou mais tarde.", "Erro", JOptionPane.ERROR_MESSAGE);
        } catch (NotBoundException ex) {
            JOptionPane.showMessageDialog(this,"Erro ao se conectar!\n Tente novamente agora ou mais tarde.", "Erro", JOptionPane.ERROR_MESSAGE);
        } catch (MalformedURLException ex) {
            JOptionPane.showMessageDialog(this,"Erro ao se conectar!\n Tente novamente agora ou mais tarde.", "Erro", JOptionPane.ERROR_MESSAGE);
        } catch (ObjectNotFoundExeption ex) {
            JOptionPane.showMessageDialog(this,"Erro ao se conectar!\n Tente novamente agora ou mais tarde.", "Erro", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButtonConnectActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ChatGUIWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ChatGUIWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ChatGUIWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ChatGUIWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ChatGUIWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonConnect;
    private javax.swing.JLabel jLabelIPPort;
    private javax.swing.JLabel jLabelIPPortLabel;
    private javax.swing.JLabel jLabelIPPortLabel1;
    private javax.swing.JLabel jLabelMaxAndConnected;
    private javax.swing.JLabel jLabelTheme;
    private javax.swing.JLabel jLabelTheme1;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTextArea jTextAreaTalks;
    private javax.swing.JFormattedTextField jTextFieldNumMaxOfClients;
    private javax.swing.JTextField jTextFieldTheme;
    // End of variables declaration//GEN-END:variables

    public void displayMessage(String mensagem) {
        jTextAreaTalks.append(mensagem +"\n");
    }
}
